

import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, Modal, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface ApprovalItem {
  id: string;
  title: string;
  initiator: string;
  initiatorDept: string;
  initiateTime: string;
  status: 'approved' | 'rejected' | 'cancelled';
  statusText: string;
  processResult: string;
  processTime: string;
  type: 'leave' | 'purchase' | 'budget' | 'expense';
  typeText: string;
  priority: 'high' | 'normal' | 'low';
}

interface FilterParams {
  result: 'all' | 'approved' | 'rejected' | 'cancelled';
  type: 'all' | 'leave' | 'purchase' | 'budget' | 'expense';
  time: 'all' | 'today' | 'week' | 'month';
}

type SortParam = 'time_desc' | 'time_asc' | 'title_asc' | 'title_desc';

const ApprovedByMeScreen = () => {
  const router = useRouter();
  
  // 模拟已审批数据
  const [originalApprovalData] = useState<ApprovalItem[]>([
    {
      id: 'APR001',
      title: '员工请假申请',
      initiator: '李小红',
      initiatorDept: '技术部',
      initiateTime: '2024-01-15 09:30',
      status: 'approved',
      statusText: '已通过',
      processResult: '通过',
      processTime: '2024-01-15 14:20',
      type: 'leave',
      typeText: '请假申请',
      priority: 'normal'
    },
    {
      id: 'APR002',
      title: '采购申请单',
      initiator: '王强',
      initiatorDept: '采购部',
      initiateTime: '2024-01-15 10:15',
      status: 'rejected',
      statusText: '已驳回',
      processResult: '驳回',
      processTime: '2024-01-15 16:45',
      type: 'purchase',
      typeText: '采购申请',
      priority: 'high'
    },
    {
      id: 'APR003',
      title: '项目预算申请',
      initiator: '陈思',
      initiatorDept: '项目部',
      initiateTime: '2024-01-14 14:30',
      status: 'approved',
      statusText: '已通过',
      processResult: '通过',
      processTime: '2024-01-14 16:20',
      type: 'budget',
      typeText: '预算申请',
      priority: 'normal'
    },
    {
      id: 'APR004',
      title: '差旅费用报销',
      initiator: '刘敏',
      initiatorDept: '市场部',
      initiateTime: '2024-01-14 11:20',
      status: 'approved',
      statusText: '已通过',
      processResult: '通过',
      processTime: '2024-01-14 15:10',
      type: 'expense',
      typeText: '费用报销',
      priority: 'normal'
    },
    {
      id: 'APR005',
      title: '设备采购申请',
      initiator: '张伟',
      initiatorDept: '技术部',
      initiateTime: '2024-01-13 16:45',
      status: 'cancelled',
      statusText: '已取消',
      processResult: '取消',
      processTime: '2024-01-14 09:30',
      type: 'purchase',
      typeText: '采购申请',
      priority: 'low'
    },
    {
      id: 'APR006',
      title: '年假申请',
      initiator: '赵敏',
      initiatorDept: '人事部',
      initiateTime: '2024-01-13 10:15',
      status: 'approved',
      statusText: '已通过',
      processResult: '通过',
      processTime: '2024-01-13 14:25',
      type: 'leave',
      typeText: '请假申请',
      priority: 'normal'
    }
  ]);

  const [approvalData, setApprovalData] = useState<ApprovalItem[]>(originalApprovalData);
  const [filteredData, setFilteredData] = useState<ApprovalItem[]>(originalApprovalData);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [isFilterModalVisible, setIsFilterModalVisible] = useState(false);
  const [isSortModalVisible, setIsSortModalVisible] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  
  const [filterParams, setFilterParams] = useState<FilterParams>({
    result: 'all',
    type: 'all',
    time: 'all'
  });
  
  const [sortParam, setSortParam] = useState<SortParam>('time_desc');

  // 筛选和排序数据
  const filterAndSortData = useCallback(() => {
    let filtered = [...originalApprovalData];
    
    // 按处理结果筛选
    if (filterParams.result !== 'all') {
      filtered = filtered.filter(item => item.status === filterParams.result);
    }
    
    // 按审批类型筛选
    if (filterParams.type !== 'all') {
      filtered = filtered.filter(item => item.type === filterParams.type);
    }
    
    // 按时间范围筛选
    if (filterParams.time !== 'all') {
      const now = new Date();
      filtered = filtered.filter(item => {
        const processDate = new Date(item.processTime);
        const diffDays = (now.getTime() - processDate.getTime()) / (1000 * 60 * 60 * 24);
        
        switch(filterParams.time) {
          case 'today': return diffDays < 1;
          case 'week': return diffDays < 7;
          case 'month': return diffDays < 30;
          default: return true;
        }
      });
    }
    
    // 排序
    filtered.sort((a, b) => {
      switch(sortParam) {
        case 'time_desc': return new Date(b.processTime).getTime() - new Date(a.processTime).getTime();
        case 'time_asc': return new Date(a.processTime).getTime() - new Date(b.processTime).getTime();
        case 'title_asc': return a.title.localeCompare(b.title);
        case 'title_desc': return b.title.localeCompare(a.title);
        default: return new Date(b.processTime).getTime() - new Date(a.processTime).getTime();
      }
    });
    
    setApprovalData(filtered);
  }, [filterParams, sortParam, originalApprovalData]);

  // 搜索功能
  const handleSearch = useCallback((keyword: string) => {
    setSearchKeyword(keyword);
    
    if (!keyword.trim()) {
      setFilteredData(approvalData);
      return;
    }
    
    const filtered = approvalData.filter(item => 
      item.title.includes(keyword) ||
      item.initiator.includes(keyword) ||
      item.typeText.includes(keyword)
    );
    
    setFilteredData(filtered);
  }, [approvalData]);

  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      filterAndSortData();
    } catch (error) {
      Alert.alert('刷新失败', '请检查网络连接后重试');
    } finally {
      setIsRefreshing(false);
    }
  }, [filterAndSortData]);

  // 加载更多
  const handleLoadMore = useCallback(async () => {
    if (isLoading) return;
    
    setIsLoading(true);
    try {
      // 模拟加载更多数据
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      Alert.alert('加载失败', '请检查网络连接后重试');
    } finally {
      setIsLoading(false);
    }
  }, [isLoading]);

  // 处理筛选应用
  const handleApplyFilter = useCallback(() => {
    setIsFilterModalVisible(false);
    filterAndSortData();
  }, [filterAndSortData]);

  // 重置筛选
  const handleResetFilter = useCallback(() => {
    setFilterParams({
      result: 'all',
      type: 'all',
      time: 'all'
    });
  }, []);

  // 处理排序应用
  const handleApplySort = useCallback((selectedSort: SortParam) => {
    setSortParam(selectedSort);
    setIsSortModalVisible(false);
    filterAndSortData();
  }, [filterAndSortData]);

  // 处理审批项点击
  const handleApprovalItemPress = useCallback((approvalId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${approvalId}`);
  }, [router]);

  // 获取状态样式
  const getStatusStyle = useCallback((status: string) => {
    switch(status) {
      case 'approved': return styles.statusApproved;
      case 'rejected': return styles.statusRejected;
      case 'cancelled': return styles.statusCancelled;
      default: return styles.statusDefault;
    }
  }, []);

  // 渲染审批项
  const renderApprovalItem = useCallback(({ item }: { item: ApprovalItem }) => (
    <TouchableOpacity
      style={styles.approvalItem}
      onPress={() => handleApprovalItemPress(item.id)}
      activeOpacity={0.7}
    >
      <View style={styles.approvalItemHeader}>
        <View style={styles.approvalItemInfo}>
          <Text style={styles.approvalItemTitle}>{item.title}</Text>
          <Text style={styles.approvalItemInitiator}>{item.initiator} | {item.initiatorDept}</Text>
        </View>
        <View style={[styles.statusBadge, getStatusStyle(item.status)]}>
          <Text style={styles.statusBadgeText}>{item.statusText}</Text>
        </View>
      </View>
      
      <View style={styles.approvalItemDetails}>
        <Text style={styles.approvalItemTime}>发起时间：{item.initiateTime}</Text>
        <Text style={styles.approvalItemResult}>{item.processResult}</Text>
      </View>
      
      <View style={styles.approvalItemFooter}>
        <View style={styles.approvalTypeTag}>
          <Text style={styles.approvalTypeText}>{item.typeText}</Text>
        </View>
        <Text style={styles.approvalProcessTime}>处理时间：{item.processTime}</Text>
      </View>
    </TouchableOpacity>
  ), [handleApprovalItemPress, getStatusStyle]);

  // 渲染空状态
  const renderEmptyState = useCallback(() => (
    <View style={styles.emptyState}>
      <View style={styles.emptyStateIcon}>
        <FontAwesome6 name="clipboard-list" size={48} color="#6B7280" />
      </View>
      <Text style={styles.emptyStateTitle}>暂无已审批记录</Text>
      <Text style={styles.emptyStateSubtitle}>您还没有处理过任何审批</Text>
    </View>
  ), []);

  // 渲染筛选模态框
  const renderFilterModal = () => (
    <Modal
      visible={isFilterModalVisible}
      transparent
      animationType="slide"
      onRequestClose={() => setIsFilterModalVisible(false)}
    >
      <View style={styles.modalOverlay}>
        <View style={styles.filterModalContent}>
          <View style={styles.modalHeader}>
            <Text style={styles.modalTitle}>筛选条件</Text>
            <TouchableOpacity
              style={styles.modalCloseButton}
              onPress={() => setIsFilterModalVisible(false)}
            >
              <FontAwesome6 name="xmark" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
          
          {/* 处理结果筛选 */}
          <View style={styles.filterSection}>
            <Text style={styles.filterSectionTitle}>处理结果</Text>
            <View style={styles.filterTagsContainer}>
              {[
                { value: 'all', label: '全部' },
                { value: 'approved', label: '已通过' },
                { value: 'rejected', label: '已驳回' },
                { value: 'cancelled', label: '已取消' }
              ].map((option) => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.filterTag,
                    filterParams.result === option.value && styles.filterTagActive
                  ]}
                  onPress={() => setFilterParams(prev => ({ ...prev, result: option.value as any }))}
                >
                  <Text style={[
                    styles.filterTagText,
                    filterParams.result === option.value && styles.filterTagTextActive
                  ]}>
                    {option.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
          
          {/* 审批类型筛选 */}
          <View style={styles.filterSection}>
            <Text style={styles.filterSectionTitle}>审批类型</Text>
            <View style={styles.filterTagsContainer}>
              {[
                { value: 'all', label: '全部类型' },
                { value: 'leave', label: '请假申请' },
                { value: 'purchase', label: '采购申请' },
                { value: 'budget', label: '预算申请' },
                { value: 'expense', label: '费用报销' }
              ].map((option) => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.filterTag,
                    filterParams.type === option.value && styles.filterTagActive
                  ]}
                  onPress={() => setFilterParams(prev => ({ ...prev, type: option.value as any }))}
                >
                  <Text style={[
                    styles.filterTagText,
                    filterParams.type === option.value && styles.filterTagTextActive
                  ]}>
                    {option.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
          
          {/* 时间范围 */}
          <View style={styles.filterSection}>
            <Text style={styles.filterSectionTitle}>时间范围</Text>
            <View style={styles.filterTagsContainer}>
              {[
                { value: 'all', label: '全部时间' },
                { value: 'today', label: '今天' },
                { value: 'week', label: '最近一周' },
                { value: 'month', label: '最近一月' }
              ].map((option) => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.filterTag,
                    filterParams.time === option.value && styles.filterTagActive
                  ]}
                  onPress={() => setFilterParams(prev => ({ ...prev, time: option.value as any }))}
                >
                  <Text style={[
                    styles.filterTagText,
                    filterParams.time === option.value && styles.filterTagTextActive
                  ]}>
                    {option.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
          
          <View style={styles.filterModalActions}>
            <TouchableOpacity
              style={styles.resetButton}
              onPress={handleResetFilter}
            >
              <Text style={styles.resetButtonText}>重置</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.applyButton}
              onPress={handleApplyFilter}
            >
              <LinearGradient
                colors={['#969FFF', '#5147FF']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
                style={styles.applyButtonGradient}
              >
                <Text style={styles.applyButtonText}>应用筛选</Text>
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );

  // 渲染排序模态框
  const renderSortModal = () => (
    <Modal
      visible={isSortModalVisible}
      transparent
      animationType="slide"
      onRequestClose={() => setIsSortModalVisible(false)}
    >
      <View style={styles.modalOverlay}>
        <View style={styles.sortModalContent}>
          <View style={styles.modalHeader}>
            <Text style={styles.modalTitle}>排序方式</Text>
            <TouchableOpacity
              style={styles.modalCloseButton}
              onPress={() => setIsSortModalVisible(false)}
            >
              <FontAwesome6 name="xmark" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
          
          <View style={styles.sortOptionsContainer}>
            {[
              { value: 'time_desc', label: '处理时间 (最新在前)' },
              { value: 'time_asc', label: '处理时间 (最旧在前)' },
              { value: 'title_asc', label: '标题 (A-Z)' },
              { value: 'title_desc', label: '标题 (Z-A)' }
            ].map((option) => (
              <TouchableOpacity
                key={option.value}
                style={styles.sortOption}
                onPress={() => handleApplySort(option.value as SortParam)}
              >
                <View style={styles.radioButtonContainer}>
                  <View style={[
                    styles.radioButton,
                    sortParam === option.value && styles.radioButtonSelected
                  ]}>
                    {sortParam === option.value && (
                      <View style={styles.radioButtonInner} />
                    )}
                  </View>
                </View>
                <Text style={styles.sortOptionText}>{option.label}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>
    </Modal>
  );

  useEffect(() => {
    filterAndSortData();
  }, [filterAndSortData]);

  useEffect(() => {
    handleSearch(searchKeyword);
  }, [approvalData, searchKeyword, handleSearch]);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <Text style={styles.headerTitle}>我已审批</Text>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={() => setIsFilterModalVisible(true)}
            >
              <FontAwesome6 name="filter" size={18} color="#6B7280" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={() => setIsSortModalVisible(true)}
            >
              <FontAwesome6 name="sort" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 搜索框 */}
        <View style={styles.searchContainer}>
          <View style={styles.searchInputWrapper}>
            <FontAwesome6 name="magnifying-glass" size={16} color="#6B7280" style={styles.searchIcon} />
            <TextInput
              style={styles.searchInput}
              placeholder="搜索审批标题、发起人..."
              placeholderTextColor="#6B7280"
              value={searchKeyword}
              onChangeText={handleSearch}
            />
          </View>
        </View>
      </View>

      {/* 审批列表 */}
      <FlatList
        data={filteredData}
        renderItem={renderApprovalItem}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            colors={['#969FFF']}
            tintColor="#969FFF"
          />
        }
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0.1}
        ListEmptyComponent={renderEmptyState}
        ListFooterComponent={
          isLoading && (
            <View style={styles.loadMoreIndicator}>
              <FontAwesome6 name="arrows-rotate" size={16} color="#969FFF" />
              <Text style={styles.loadMoreText}>加载中...</Text>
            </View>
          )
        }
      />

      {/* 筛选模态框 */}
      {renderFilterModal()}

      {/* 排序模态框 */}
      {renderSortModal()}
    </SafeAreaView>
  );
};

export default ApprovedByMeScreen;

